/**
 * 
 */
package cn.x6game.socket.handler;

import java.util.List;
import java.util.concurrent.atomic.AtomicLong;

import org.apache.log4j.Logger;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelUpstreamHandler;

import com.app.framework.socket.Packet;

/**
 * @author lisong
 * @version 2013-2-26 下午2:18:29
 */
public class SocketCSUpstreamHandler extends SimpleChannelUpstreamHandler {

	private static final Logger logger = Logger.getLogger(SocketCSUpstreamHandler.class);
	public static AtomicLong rece = new AtomicLong();
	@Override
	public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)
			throws Exception {

		@SuppressWarnings("unchecked")
		List<Packet> lst = (List<Packet>)e.getMessage();
		for(int i=0;i<lst.size();i++) {
			Packet packet = lst.get(i);
			logger.error("客户端收到服务器消息:type:"+packet.getType()+" msg:"+new String(packet.getContent()));
		}
		rece.incrementAndGet();
		
	}
	@Override
	public void channelInterestChanged(ChannelHandlerContext ctx,
			ChannelStateEvent e) throws Exception {
		if(e.getChannel().isWritable()) {
			synchronized (e.getChannel().getAttachment()) {
				e.getChannel().getAttachment().notify();
			}
			
		}
	}
	@Override
	public void channelOpen(ChannelHandlerContext ctx, ChannelStateEvent e)
			throws Exception {
		if(logger.isDebugEnabled()) {
			logger.debug("client opend");
		}
		e.getChannel().setAttachment(new Object());
	}
	
	@Override
	public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e)
			throws Exception {
		if(logger.isDebugEnabled()) {
			logger.debug("client connected");
		}
	}
	@Override
	public void channelDisconnected(ChannelHandlerContext ctx,
			ChannelStateEvent e) throws Exception {
		logger.error("channel closed:"+e.getChannel());
	}
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e)
			throws Exception {
		
		e.getCause().printStackTrace();
		
		logger.error(e.getCause());
		
	}
}
